#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h> 
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <time.h>
#include "temper.h"



int get_temperature(float *temp)
{
    int fd = -1;
    char buf[128];
    char *ptr = NULL;
    DIR *dirp = NULL;
    struct dirent *direntp = NULL;
    char w1_path[64] = "/sys/bus/w1/devices/";
    char chip_sn[32];
    int found = 0;

    dirp = opendir(w1_path);
    if(!dirp)
    {
        printf("open folder %s failure: %s\n", w1_path, strerror(errno));
        return -1;
    }
    
    while((direntp = readdir(dirp)) != NULL)
    {
        if(strstr(direntp->d_name, "28-"))
        {
            strncpy(chip_sn, direntp->d_name, sizeof(chip_sn)-1);
            chip_sn[sizeof(chip_sn)-1] = '\0';
            found = 1;
            break;
        }
    }

    closedir(dirp);

    if(!found)
    {
        printf("Cannot find ds18b20 chipset\n");
        return -2;
    }

    strncat(w1_path, chip_sn, sizeof(w1_path)-strlen(w1_path)-1);
    strncat(w1_path, "/w1_slave", sizeof(w1_path)-strlen(w1_path)-1);

    if((fd = open(w1_path, O_RDONLY)) < 0)
    {
        printf("open file failure: %s\n", strerror(errno));
        return -3;
    }

    memset(buf, 0, sizeof(buf));
    if(read(fd, buf, sizeof(buf)-1) < 0)
    {
        printf("read data from fd=%d failure: %s\n", fd, strerror(errno)); 
        close(fd);
        return -4;
    }

    ptr = strstr(buf, "t=");
    if(!ptr)
    {
        printf("Cannot find t= string\n");
        close(fd);
        return -5;
    }

    ptr += 2;
    *temp = atof(ptr)/1000.0;

    close(fd);
    return 0;
}

int get_humidity(float *humidity)
{
    const char *humidity_path = "/sys/bus/w1/devices/";
    FILE *fp = NULL;
    char buffer[32];
    int raw_value;
    
    fp = fopen(humidity_path, "r");
    if(!fp) {
        perror("Failed to open humidity sensor");
        return -1;
    }
    
    if(!fgets(buffer, sizeof(buffer), fp)) {
        fclose(fp);
        return -2;
    }
    
    fclose(fp);
    
    raw_value = atoi(buffer);
    *humidity = raw_value / 1000.0f;
    
    if(*humidity > 100.0f) *humidity = 100.0f;
    if(*humidity < 0.0f) *humidity = 0.0f;
    
    return 0;
}
